/*
 * @Author: hashMi 854059946@qq.com
 * @Date: 2023-10-29 10:19:37
 * @LastEditors: hashMi 854059946@qq.com
 * @LastEditTime: 2023-11-01 21:38:51
 * @FilePath: /guiguzhenxuan/src/store/modules/user.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { defineStore } from 'pinia'
import { reqLogin, reqUserInfo, reqLogout } from '@/api/user'
import type { loginFormData, loginResponseData } from '@/api/user/type'
import type { UserState } from '@/store/types/type'
import { SET_TOKEN, GET_TOKEN } from '@/utils/token'
import { constantRoutes } from '@/router/routes'

const useUserStore = defineStore('user', {
  state: (): UserState => ({
    token: GET_TOKEN(),
    menuList: constantRoutes,
    username: '',
    avatar: '',
  }),
  actions: {
    // 用户登录信息token
    async userLogin(data: loginFormData) {
      const userResult: loginResponseData = await reqLogin(data)
      if (userResult.code === 200) {
        SET_TOKEN(userResult.data)
      } else {
        return Promise.reject(new Error(userResult.message))
      }
    },

    // 获取拥护信息
    async getUserInfo() {
      const userInfo = await reqUserInfo()
      console.log('拥护信息', userInfo)
      if (userInfo.code === 200) {
        this.username = userInfo.data?.name
        this.avatar = userInfo.data?.avatar
      }
    },

    //退出登录
    async userLoginOut() {
      await reqLogout()
      this.token = ''
      this.avatar = ''
      this.username = ''
    },
  },

  getters: {},
})

export default useUserStore
